package com.foresee.security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.Key;
import java.security.SecureRandom;

/**
 * 对称加密工具
 * 由于RSA加密方式 加密的数据有限制 一般小于keySize 120个字节
 * keySieze过大 会导致 解密时间过长
 * 所以使用AES DES 对称加密 key使用RSA加密  来解决问题
 * @author syk
 */
public class AESDESUtils {

    /** 可选项 AES DES DESede*/
    private static String DES = "AES";
    /**
     * 可选项 AES DES DESede
     */
    private static String CIPHER_ALGORITHM = "AES";


    public static Key getSecretKey(String key) throws Exception {
        SecretKey secretKey = null;
        key = key!=null?key:"";
        KeyGenerator keyGenerator = KeyGenerator.getInstance(DES);
        keyGenerator.init(new SecureRandom(key.getBytes()));
        secretKey = keyGenerator.generateKey();

        return secretKey;
    }

    /**
     * 加密
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static String encrypt(String data,String key) throws Exception {
        SecureRandom sr = new SecureRandom();
        Key securekey = getSecretKey(key);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
        byte[] bt = cipher.doFinal(data.getBytes("UTF-8"));
        String strs = parseByte2HexStr(bt);
        return strs;
    }

    /**
     * 解密
     * @param message
     * @param key
     * @return
     * @throws Exception
     */
    public static String decrypt(String message,String key) throws Exception{
        byte[] decode = parseHexStr2Byte(message);

        SecureRandom sr = new SecureRandom();
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        Key securekey = getSecretKey(key);
        cipher.init(Cipher.DECRYPT_MODE, securekey,sr);
        byte[] res = cipher.doFinal(decode);
        return new String(res,"UTF-8");
    }


    /**
     * 将二进制转换成16进制(中文乱码 aes 需要16进制)
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }



}
